var baseURL = "/hlht/";

//登录token
var token = localStorage.getItem("token");

//暂时先屏蔽掉
//if(token == null){
    if(location.href.indexOf("sec=") != -1){
        var sec = location.href.split("sec=")[1];
        $.ajax({
            type: "POST",
            dataType: "json",
            async:false,
            url: "login?sec="+sec,
            success: function (jsonData) {
                if (jsonData.code == 200) {//登录成功
                    console.info("sec:"+new Date());
                    localStorage.setItem("token", jsonData.token);
                    localStorage.setItem("userName", jsonData.userName);
                    //location.href = 'index.html?sec='+sec;
                    location.href = 'index.html';
                }
            }
        });
    //}else{
       // location.href = baseURL + 'login.html';
   // }

}

//jquery全局配置
$.ajaxSetup({
    dataType: "json",
    cache: false,
    headers: {
        "token": token
    },
    complete: function(xhr) {
        //token过期，则跳转到登录页面
        if(xhr.responseJSON !=undefined && xhr.responseJSON.code == 401){
            if(location.href.indexOf("sec=") != -1){
                var sec = location.href.split("sec=")[1];
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    async:false,
                    url: "login?sec="+sec,
                    success: function (jsonData) {
                        if (jsonData.code == 200) {//登录成功
                            console.info("sec:"+new Date());
                            localStorage.setItem("token", jsonData.token);
                            localStorage.setItem("userName", jsonData.userName);
                            location.href = 'index.html';
                        }
                    }
                });
            }else{
                location.href = baseURL + 'login.html';
            }
        }
    }
});



/**
 * 通用类
 */
var Common = {

    /**
     * ajax请求封装
     * @param url 请求路径：相对路径
     * @param paramObj 请求参数列表O
     * @param succCallBackFunction 成功的回调函数：异步请求下，才会调用
     * @param isAsync  是否异步，默认为true，异步； false为同步
     * @param type    请求方法名称，post get put delete（TEST）
     * @param dataType  json格式
     */
    ajaxHandler: function (url, paramObj, isAsync, type) {
        //如果上层不传入具体的值，则默认为异步，(默认: true) 默认设置下，所有请求均为异步请求
        if (isAsync == null || isAsync == "") {
            isAsync = true;
        }

        if (type == null || isAsync == "") {

        }

        $.ajax({
            url: url,
            type: type,
            dataType: "json",
            success: function (jsonData) {

            }
        });
    },

    /**
     * 请求参数获取
     */
    GetRequest: function() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        str = str.split("&");
        for(var i = 0; i < str.length; i ++) {
            theRequest[str[i].split("=")[0]]=unescape(str[i].split("=")[1]);
        }
    }
    return theRequest;
    },

    GetRequestWithChinese: function() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            str = str.split("&");
            for(var i = 0; i < str.length; i ++) {
                theRequest[str[i].split("=")[0]]=decodeURIComponent(str[i].split("=")[1]);
            }
        }
        return theRequest;
    },

    /**
     * JS正则表达式验证是否为11位有效手机号码
     * @returns {boolean}
     */
    isPoneAvailable:function (tele) {
        var myreg=/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
        if (tele !=""&& tele !=undefined  && !myreg.test(tele)) {
            return false;
        } else {
            return true;
        }
    },

    /**
     * 获取 数据源值域目录数椐
     * @param zydm 值域代码
     * @param selectId 下拉框ID
     * demo   Common.GetSjyzy("CV02.01.101","testSelect");
     */
    GetSjyzy: function(zydm,selectId) {

        if(zydm!=null&&zydm!="")
        {
            $.ajax({
                type: "GET",
                contentType: 'application/x-www-form-urlencoded',
                async:false,
                dataType: "json",
                url: "commonapi/zyinfo",
                data:
                {
                    zydm:zydm
                },
                success: function (jsonData) {
                    if (jsonData.code == 200) {   //查询成功
                        var list = jsonData.sjyzymlEntity;
                        var optionhtml = '<option  value="" ></option>';
                        if(list.length >0){
                            for (var i = 0; i < list.length; i++) {
                                var data = list[i];
                                optionhtml +='<option  value= "' + data.zdm +'" >' + data.zmc + '</option>';
                            }
                        }
                        $('#'+selectId).append(optionhtml);

                    }
                }
            });

        }

    },

    /***
     * 获取管理年度
     */
    initGlnd:function (glndId) {
        var myDate = new Date();
        var dqnd = myDate.getFullYear().toString();
        var list = new Array()
        list[0] = dqnd;
        list[1] = dqnd-1;
        list[2] = dqnd-2;
        list[3] = dqnd-3;
        list[4] = dqnd-4;

        var optionhtml = '';
        if(list.length >0){
            for (var i = 0; i < list.length; i++) {
                var data = list[i];
                optionhtml +='<option value="'+data+'">' + data + '</option>';
            }
        }
        $('#'+glndId).append(optionhtml);
    },

    /**
     * 功能按钮-权限过滤
     *
     */
    qxGnan: function() {

        if(mcode !=undefined && mcode!=null)
        {
            $.ajax({
                type: "GET",
                contentType: 'application/json',
                dataType: "json",
                url: "commonapi//getCzryqx/"+mcode,
                success: function (jsonData) {
                    if (jsonData.code == 200) {
                        var noQxlist = jsonData.noQxlist;
                        var reg = new RegExp(":","g");
                        if(noQxlist.length >0) {
                            $.each(noQxlist, function (index, entity) {
                                var temp = entity.gndm.replace(reg,"");
                                if($("."+temp).length>0)
                                {
                                    $("."+temp).removeAttr('href');//去掉a标签中的href属
                                    $("."+temp).removeAttr('onclick');//去掉a标签中的onclick事件
                                    $("."+temp).css("opacity","0.2");
                                }
                            })
                        }

                    }
                }
            });
        }

    },

    /**
     * 身份证校验
     * @param zjhm
     * @returns {boolean}
     */
    jySfzh:function(zjhm){
        var code = zjhm;
        var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
        var tip = "";
        var pass= true;

        if(!code){
            tip = "身份证号不能为空";
            pass = false;
        }else if(/**!code ||**/ !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
            tip = "身份证号格式错误";
            pass = false;
        }

        else if(!city[code.substr(0,2)]){
            tip = "地址编码错误";
            pass = false;
        }
        else{
            //18位身份证需要验证最后一位校验位
            if(code.length == 18){
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                //校验位
                var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++)
                {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if(parity[sum % 11] != code[17]){
                    tip = "校验位错误";
                    pass =false;
                }
            }
        }
        if(!pass) {
            LayerWn.showFailAlert(tip,0);
            //$("#"+id).focus();
        }//alert(tip);
        return pass;
    },

    /**
     * 根据身份证号码计算出生日期
     * @param zjhm
     * @returns {string}
     */
    jsCsrq:function(zjhm){
        var csrq = "";
        var n = "";
        var y = "";
        var r = "";
        if(zjhm.length == 15){
            n = "19"+zjhm.substring(6,8);
            y = zjhm.substring(8,10);
            r = zjhm.substring(10,12);
        }else if(zjhm.length == 18){
            n = zjhm.substring(6,10);
            y = zjhm.substring(10,12);
            r = zjhm.substring(12,14);
        }
        csrq = n+""+y+""+r;
        return csrq;
    },

    /**
     * 根据身份证号码计算性别
     * @param zjhm
     */
    jsXb:function(zjhm){
        var xbdm = "";
        if(zjhm.length == 15) {
            if (parseInt(zjhm.substring(14, 15)) % 2 == 1)
                xbdm = "1";
            else
                xbdm = "2";
        }else if(zjhm.length == 18){
            if(parseInt(zjhm.substring(16,17))%2 == 1)
                xbdm = "1"
            else
                xbdm = "2";
        }
        return xbdm;
    },

    jyNumberic:function(id,length,precLen,name){
        var value = $("#"+id).val();
        //var message = "数字型"+name+"输入错误。长度应为:"+length;
        //eval("var reg = ^(?!^0*(\.0{1,2})?$)^\d{1,"+length+"}(\.\d{1,"+precLen+"})?$/;");
        //eval("var reg1 = /^(?!^0*(\\.0{1,2})?$)^\\d{1,13}(\\.\\d{1,2})?$/;");
        if(value!=null && value != "" && value != 0){
            if(precLen && precLen != 0){
                eval("var reg = /^(?!^0*(\\.0{1,2})?$)^\\d{1,"+(length-precLen)+"}(\\.\\d{1,"+precLen+"})?$/;");
                //message += ",精度应为:"+precLen;
            }else{
                eval("var reg = /^(?!^0*(\\.0{1,2})?$)^\\d{1,"+length+"}$/;");
            }
            return reg.test(value);
        }
        return true;

            //LayerWn.showFailAlert(message,0);
            //return false;
        //}
    }

};


//form表单序列化
(function($){
    $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        var str=this.serialize();

        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });

        var $radio = $('input[type=radio],input[type=checkbox]',this);
        $.each($radio,function(){
            if(!serializeObj.hasOwnProperty(this.name)){
                serializeObj[this.name] = '0';
            }
        });

        return serializeObj;
    };
})(jQuery);


//全局参数，三级菜单编码
var mcode = null;

// //按钮权限验证
// $(function () {
//     if("third"==Common.GetRequest().cdType){
//         mcode =  Common.GetRequest().mcode;
//     }
//     if(mcode !=undefined && mcode!=null)
//     {
//         $.ajax({
//             type: "GET",
//             contentType: 'application/json',
//             dataType: "json",
//             url: "commonapi//getCzryqx/"+mcode,
//             success: function (jsonData) {
//                 if (jsonData.code == 200) {
//                     var noQxlist = jsonData.noQxlist;
//                     var reg = new RegExp(":","g");
//                     if(noQxlist.length >0) {
//                         $.each(noQxlist, function (index, entity) {
//                             if(entity.url!=null)
//                             {
//                                 var temp = entity.url.replace(reg,"");
//                                 if($("#"+temp).length>0)
//                                 {
//                                     $("#"+temp).attr('disabled',true);
//                                 }
//                             }
//
//                         })
//                     }
//
//                 }
//             }
//         });
//     }
// });

